package org.kugua.font.provider;

import java.awt.*;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.kugua.common.Constants;
import org.kugua.enums.FontEnum;
import org.kugua.font.FontProvider;
import org.springframework.core.io.ClassPathResource;

/**
 * LocalFontProvider
 *
 * @author 苦瓜
 * @create 2024-08-29
 * @since 1.0.0
 */
@Slf4j
public class LocalFontProvider implements FontProvider {

    /**
     * 字体cache
     */
    private static final Map<String, Font> FONT_MAP = new HashMap<>();

    static {
        try {
            FontEnum[] values = FontEnum.values();
            for (FontEnum r : values) {
                ClassPathResource classPathResource = new ClassPathResource(Constants.Path.FONT_PATH + File.separator + r.getFileName());
                if (!classPathResource.exists()) {
                    log.warn("font not exist.name {}", r.getFileName());
                    continue;
                }
                Font font = Font.createFont(Font.TRUETYPE_FONT, classPathResource.getInputStream())
                        .deriveFont(Font.BOLD, r.getSize());
                FONT_MAP.putIfAbsent(r.getName(), font);
            }
        } catch (Exception e) {
            log.error("init loading font failed.", e);
        }
    }


    /**
     * 获取指定的字体
     *
     * @param name 字体名称
     * @return Font
     */
    @Override
    public Font get(String name) {
        return FONT_MAP.get(name);
    }

    /**
     * 获取指定的字体，如果字体
     *
     * @param name 字体名
     * @param defaultFont 默认字体
     * @return Font
     */
    @Override
    public Font get(String name, Font defaultFont) {
        return FONT_MAP.getOrDefault(name, defaultFont);
    }
}
